<?php
declare (strict_types = 1);

namespace app\middleware;

use app\infrastructure\enum\ResponseCode;

class ParamValidate
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     *
     * @return \think\response\Json
	 */
    public function handle($request, \Closure $next)
    {
		$controller = $request->controller();
		$filePath = APP_PATH . 'agent/validate/'. $controller. 'Validate.php';
		if (file_exists($filePath)) {
			$filePath = explode('.', $filePath);
			$class = str_replace('/', '\\', $filePath[2]);
			$scene = $request->action();
			$validate = new $class();
			if (!$validate->scene($scene)->check($request->param())) {
				$error = $validate->getError();
				$msg = '请求参数错误';
				if (is_string($error)){
					$msg = $error;
				} elseif (is_array($error)){
					$msg = json_encode($error);
				}
				$result = [
					'code' => ResponseCode::PARAM_ERR,
					'msg'  => $msg,
					'time' => $request->server('REQUEST_TIME'),
					'data' => null,
				];
				return json($result);
			}
			$request->data = $request->only($validate->getOnly());
		}
		return $next($request);
    }

}
